package krautz.fitness;

import java.io.File;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.krautzlabs.R;

public class WeightThingyActivity extends Activity {
    public static final int TAKE_PICTURE = 0;
    
    private WeightDatabase db;
    
	private Uri imageUri;
	private Bitmap imageSave;
	private EditText dateTime;
	private EditText weight;
	private EditText fat;
	private EditText water;
	private EditText muscle;
	private EditText visceral;
	private EditText comments;
	
	private Activity activity;
	
	//temporary date stuff
	private int month;
	private int day;
	private int year;
	DatePickerDialog.OnDateSetListener dateListener;
	
	//dialog ints
	final int DATE_DIALOG_ID = 0;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        activity = this;
        
        Button picButton = (Button)findViewById(R.id.pictureButton);
        ButtonListener bL = new ButtonListener();
        picButton.setOnClickListener(bL);
        
        Button submitButton = (Button)findViewById(R.id.submitButton);
        submitButton.setOnClickListener(bL);
        
        dateTime = (EditText)findViewById(R.id.dateField);
        weight = (EditText)findViewById(R.id.weightField);
        fat = (EditText)findViewById(R.id.fatField);
        water = (EditText)findViewById(R.id.waterField);
        muscle = (EditText)findViewById(R.id.muscleField);
        visceral = (EditText)findViewById(R.id.visceralField);
        comments = (EditText)findViewById(R.id.commentsField);
        
        //initialize datefield
        final Calendar c = Calendar.getInstance();
        this.month = c.get(Calendar.MONTH);
        this.day = c.get(Calendar.DAY_OF_MONTH);
        this.year = c.get(Calendar.YEAR);
        dateTime.setText((month+1)+"-"+day+"-"+year);
        dateTime.setInputType(0);//stop keyboard from popping up
        dateTime.setOnFocusChangeListener(new OnFocusChangeListener(){

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
		            showDialog(DATE_DIALOG_ID);
		        }
			}

        });
        
        dateTime.setOnTouchListener(new OnTouchListener(){

			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
		            showDialog(DATE_DIALOG_ID);
		        }
				return false;
			}
        	
        	
        });
        
        dateListener =
                new DatePickerDialog.OnDateSetListener() {

                    public void onDateSet(DatePicker view, int myear, 
                                          int monthOfYear, int dayOfMonth) {
                        year = myear;
                        month = monthOfYear;
                        day = dayOfMonth;
                        dateTime.setText((month+1)+"-"+day+"-"+year);
                    }
                };
        
                
        
        db = new WeightDatabase(this);
        db.open();
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	switch(requestCode){
    		case TAKE_PICTURE:
    			if (resultCode == Activity.RESULT_OK) {
    				ContentResolver cr = getContentResolver();
    	            try {
    	                imageSave = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
    	                File file = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    	                if(!file.delete()){
    	                	Log.i("logMarker", "Failed to delete " + file);
    	                }
    	                Toast.makeText(this, imageUri.toString(),Toast.LENGTH_LONG).show();
    	            } catch (Exception e) {
    	                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
    	                Log.e("Camera", e.toString());
    	            }
    	        }
    	}
    }
    
    
    private class ButtonListener implements OnClickListener{

		public void onClick(View v) {
			
			switch(v.getId()){
				case R.id.pictureButton:
					Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
				    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
				    imageUri = Uri.fromFile(photo);
				    startActivityForResult(intent, TAKE_PICTURE);
				    break;
				    
				case R.id.submitButton:
					WeightRecord record = new WeightRecord(dateTime.getText().toString(), weight.getText().toString(), fat.getText().toString(), water.getText().toString(), visceral.getText().toString(), muscle.getText().toString(), imageSave, comments.getText().toString());
					if(db.createWeightRecord(record) < 0){
						Toast.makeText(activity, "Failed to create record", Toast.LENGTH_LONG).show();
					}
					
					ImageView iv = new ImageView(activity);
					iv.setImageBitmap(imageSave);
					activity.setContentView(iv);
					break;
			}
		}
    }
    
    protected Dialog onCreateDialog(int id)
    {
    	switch(id)
    	{
	    	case DATE_DIALOG_ID:
		    	return new DatePickerDialog(this,
		    			dateListener,
		                year, month, day);
    	}
    	return null;
    }
}